﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ERP.Manager.BusinessServices;
using ERP.Manager.Controllers.CustomAttributes;
using ERP.Manager.DataEntity;

namespace ERP.Manager.Controllers
{
    [CheckLoginAttribute]
    public class WorkController : Controller
    {
        private readonly WorkinfoService workservice;
        private readonly DepartmentService departmentservice;
        private readonly UserinfoService userservice;
        private readonly ContextService contextservcie;
        public WorkController() { }
        public WorkController(WorkinfoService workservice, DepartmentService departmentservice, UserinfoService userservces, ContextService contextservice)
        {
            this.workservice = workservice;
            this.departmentservice = departmentservice;
            this.userservice = userservces;
            this.contextservcie = contextservice;
        }

        #region 显示接收信息页面
        [CheckLoginAttribute]
        public ActionResult ShowinceptWork(int? page)
        {
            var userinfo = ContextService.Current;
            int pagecount = page ?? 1;
            List<WorkInfo> list = workservice.getWorksByToUserId(userinfo.UserId);
            int count = list.Count;
            foreach (var item in list)
            {
                if (item.endtime < DateTime.Now.AddDays(0))
                {
                    workservice.updateworkinfostatus(userinfo.UserId);
                }
            }
            List<WorkInfo> lists = workservice.getworkinfobyuseridpagecount(userinfo.UserId, pagecount);
            ViewData["count"] = count;
            ViewData["wordinfo"] = lists;

            return View();
        }
        #endregion

        #region 显示发布信息页面
        [CheckLoginAttribute]
        public ActionResult ShowreleaseWork(int? page)
        {
            var userinfo = ContextService.Current;
            if (userinfo.UserId != null)
            {
                int pagecount = page ?? 1;
                List<WorkInfo> list = workservice.getWorksByFromUserId(userinfo.UserId, pagecount);
                int count = workservice.getworkinfobyreleaseworkcount(userinfo.UserId);
                ViewData["count"] = count;
                ViewData["wordinfo"] = list;
            }
            else
            {
                return this.RedirectToAction("Login", "Home");
            }
            return View();
        }
        #endregion

        #region 添加发布信息页面
        public ActionResult AddWork()
        {
            ViewData["department"] = departmentservice.getDepartments();
            List<UserInfo> listuser = userservice.getAllUsers();
            ViewData["userinfoname"] = listuser;
            return View();
        }
        #endregion

        #region Ajax添加发布信息页面
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public string AjaxAddWork(string fromuserid, string title, string content, string touserid, string begindate, string enddate)
        {
            try
            {
                int rowcount = 0;
                WorkInfo work = new WorkInfo();
                work.title = title;
                work.workContent = content;
                work.userInfo.userId = fromuserid;
                work.publishDate = DateTime.Now.AddDays(0);
                work.status = 1;
                work.updateDate = DateTime.Now.AddDays(0);
                work.starttime = DateTime.Parse(begindate);
                work.endtime = DateTime.Parse(enddate);
                work.workinfoNote = "";
                work.accessories = "";
                string[] userid = touserid.Split(',');
                for (int i = 0; i < userid.Length; i++)
                {
                    work.toUserId = userid[i];
                    rowcount = workservice.addWork(work);
                }
                if (rowcount > 0)
                {
                    System.Threading.Thread.Sleep(1000);
                    return "success";
                }
                else
                {
                    System.Threading.Thread.Sleep(1000);
                    return "error";
                }
            }
            catch (Exception ex)
            {
                System.Threading.Thread.Sleep(1000);
                return "" + ex.Message;
            }
        }
        #endregion

        #region 进行中的工作管理页面
        public ActionResult ShowprocessoperationWork(int? page)
        {
            var userinfo = ContextService.Current;
            if (userinfo.UserId != null)
            {
                int pagecount = page ?? 1;
                List<WorkInfo> list = workservice.allworkinfojinxing(userinfo.UserId, pagecount);
                int count = workservice.allworkifojinxingcount(userinfo.UserId);
                ViewData["count"] = count;
                ViewData["wordinfo"] = list;
            }
            else
            {
                return this.RedirectToAction("Login", "Home");
            }
            return View();
        }
        #endregion

        #region 完成工作管理页面
        public ActionResult ShowachieveWork(int? page)
        {
            var userinfo = ContextService.Current;
            if (userinfo.UserId != null)
            {
                int pagecount = page ?? 1;
                List<WorkInfo> list = workservice.allworkinfowancheng(userinfo.UserId, pagecount);
                int count = workservice.allworkinfowanchengcount(userinfo.UserId);
                ViewData["count"] = count;
                ViewData["wordinfo"] = list;
            }
            else
            {
                return this.RedirectToAction("Login", "Home");
            }
            return View();
        }
        #endregion

        #region 超期工作管理
        public ActionResult ShowOverdueWork(int? page)
        {
            var userinfo = ContextService.Current;
            if (userinfo.UserId != null)
            {
                int pagecount = page ?? 1;
                List<WorkInfo> list = workservice.allworkinfochaoqi(userinfo.UserId, pagecount);
                int count = workservice.allworkinfochaoqicount(userinfo.UserId);
                ViewData["count"] = count;
                ViewData["wordinfo"] = list;
            }
            else
            {
                return this.RedirectToAction("Login", "Home");
            }
            return View();
        }
        #endregion

        #region 显示接收信息的详细信息页面
        public ActionResult ShowinceptWorkDetail()
        {
            //获取上一次请求的地址；
            string url = Request.UrlReferrer.AbsolutePath;
            string a = "";
            if (url == "/Work/ShowinceptWork")
            {
                a += "<a onclick='javascript:history.go(-1);' style='color: white'>接收工作管理</a>";
            }
            else if (url == "/Work/ShowprocessoperationWork")
            {
                a += "<a onclick='javascript:history.go(-1);'' style='color: white'>进行工作管理</a>";
            }
            else if (url == "/Work/ShowachieveWork")
            {
                a += "<a onclick='javascript:history.go(-1);' style='color: white'>完成工作管理</a>";
            }
            else
            {
                a += "<a onclick='javascript:history.go(-1);' style='color: white'>超期工作管理</a>";
            }
            ViewData["a"] = a;
            int workid = int.Parse(Request.QueryString["workid"]);
            var userinfo = ContextService.Current;
            if (userinfo.UserId != null)
            {
                WorkInfo wordinfo = workservice.getworkinfobyuseriddetail(userinfo.UserId, workid);
                ViewData["wordinfo"] = wordinfo;
            }
            else
            {
                return this.RedirectToAction("Login", "Home");
            }
            return View();
        }
        #endregion

        #region 显示发布消息的详细信息页面
        public ActionResult ShowreleaseWorkDetail()
        {
            int workid = int.Parse(Request.QueryString["workid"]);
            var userinfo = ContextService.Current;
            if (userinfo.UserId != null)
            {
                WorkInfo wordinfo = workservice.getworkinfobyreleaseworkdetail(userinfo.UserId, workid);
                ViewData["wordinfo"] = wordinfo;
            }
            else
            {
                return this.RedirectToAction("Login", "Home");
            }
            return View();
        }
        #endregion

        #region 修改发布信息页面
        public ActionResult releaseWorkUpdate()
        {
            ViewData["department"] = departmentservice.getDepartments();
            List<UserInfo> listuser = userservice.getAllUsers();
            ViewData["userinfoname"] = listuser;
            int workid = int.Parse(Request.QueryString["workid"]);
            var userinfo = ContextService.Current;
            if (userinfo.UserId != null)
            {
                WorkInfo wordinfo = workservice.getworkinfobyreleaseworkdetail(userinfo.UserId, workid);
                ViewData["wordinfo"] = wordinfo;
            }
            else
            {
                return this.RedirectToAction("Login", "Home");
            }
            return View();
        }
        #endregion

        #region Ajax修改发布信息
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public string AjaxreleaseWorkUpdate(string workid, string title, string content, string touserid, string begindate, string enddate)
        {
            try
            {
                WorkInfo work = new WorkInfo();
                work.workId = int.Parse(workid);
                work.title = title;
                work.workContent = content;
                work.toUserId = touserid;
                work.starttime = DateTime.Parse(begindate);
                work.endtime = DateTime.Parse(enddate);
                int rowcount = workservice.updateWork(work);
                if (rowcount > 0)
                {
                    System.Threading.Thread.Sleep(1000);
                    return "success";
                }
                else
                {
                    System.Threading.Thread.Sleep(1000);
                    return "error";
                }
            }
            catch (Exception ex)
            {
                System.Threading.Thread.Sleep(1000);
                return ex.Message;
            }
        }
        #endregion

        #region 删除发布信息的方法
        [AcceptVerbs(HttpVerbs.Post)]
        public string deletereleaseWork(string workid)
        {
            try
            {
                int workids = int.Parse(workid.ToString());
                int rowcount = workservice.deleteWorkById(workids);
                if (rowcount > 0)
                {
                    return "success";
                }
                else
                {
                    return "error";
                }
            }
            catch (Exception ex)
            {
                return  ex.Message;
            }
        }
        #endregion        

        #region 实现级联下拉框绑定 根据部门编号查询用户姓名的方法
        public string ALLDepartmentid_userName(string departmentID)
        {
            string html = "";
            DepartmentInfo department = new DepartmentInfo();
            department.departmentId = departmentID.ToString();
            List<UserInfo> list = userservice.ALLDepartmentid_userName(department);
            foreach (var item in list)
            {
                if (contextservcie.UserId != item.userId)
                {
                    html += "<option value=" + item.userId + ">" + item.userName + "</option>";
                }
            }
            return html;
        }
        #endregion

        #region 修改工作的任务状态的方法
        public string updateworkstatus(string workid, string status)
        {
            WorkInfo work = new WorkInfo();
            work.workId = int.Parse(workid);
            work.status = int.Parse(status);
            work.updateDate = DateTime.Now.AddDays(0);
            int rowcount = workservice.updateworkstatus(work);
            try
            {
                if (rowcount > 0)
                {
                    return "success";
                }
                else
                {
                    return "error";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion

        #region 进行的工作修改为已完成然后添加完成任务的备注信息
        public string updateworkstatusandworkinfonote(string workid, string status, string workinfonote)
        {
            WorkInfo work = new WorkInfo();
            work.workId = int.Parse(workid);
            work.status = int.Parse(status);
            work.updateDate = DateTime.Now.AddDays(0);
            work.workinfoNote = workinfonote;
            int rowcount = workservice.updateworkstatusandworkinfonote(work);
            try
            {
                if (rowcount > 0)
                {
                    return "success";
                }
                else
                {
                    return "error";
                }
            }
            catch (Exception ex)
            {
                return ex.Message.Contains("DELETE 语句与 REFERENCE 约束") ? "抱歉，修改任务状态失败！" : ex.Message;
            }
        }
        #endregion
    }
}
